package com.yami.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ResponseEnum;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.StringUtils;
import com.yami.shop.dto.group.ChannelDTO;
import com.yami.shop.dto.group.GroupChannelDTO;
import com.yami.shop.dto.user.GroupNotificationMessageDTO;
import com.yami.shop.security.common.bo.UserInfoInTokenBO;
import com.yami.shop.security.common.util.AuthUserContext;
import com.yami.shop.service.*;
import com.yami.shop.util.SendUtil;
import io.rong.RongCloud;
import io.rong.methods.ultragroup.channel.BusChannel;
import io.rong.methods.ultragroup.notdisturb.Notdisturb;
import io.rong.models.Result;
import io.rong.models.response.NotdisturbStatusResult;
import io.rong.models.ultragroup.UltraGroupMember;
import io.rong.models.ultragroup.UltraGroupModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;

import java.util.*;
import java.util.stream.Collectors;

import static com.yami.shop.common.response.ServerResponseEntity.success;

/**
 * 超级群聊频道
 */

@Service
@Slf4j
public class RongYunChannelServiceImpl {

    @Autowired
    private RongCloud rongCloud;

    @Autowired
    private MeltCloudChannelService channelService;

    @Autowired
    private MeltCloudGroupServiceImpl groupService;

    @Autowired
    private MeltCloudGroupUserService groupUserService;
    
    @Autowired
    private MeltCloudChannelUserService channelUserService;

    @Autowired
    private RongYunMsgServiceImpl rongYunMsgService;

    @Autowired
    private MeltCloudUserService userService;
    
    @Autowired
    private MeltCloudChannelUserGroupService channelUserGroupService;
    
    @Autowired
    private MeltCloudUsergroupUserService usergroupUserService;
    
    private BusChannel busChannel;
    
    private Notdisturb notdisturb;

    @PostConstruct
    public void init() {
        this.busChannel = rongCloud.ultraGroup.busChannel;
        this.notdisturb = rongCloud.ultraGroup.notdisturb;
    }
    
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity create(ChannelDTO channelDTO) throws Exception {
        String currentUserId = operationPermissionVerify(channelDTO.getGroupId(), true, null);
        ultraGroupExpireCheck(channelDTO.getGroupId(), currentUserId, null);
        MeltCloudGroup group = groupService.getById(channelDTO.getGroupId());
        if (group == null || group.getIsDismiss().equals("1")) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "超级群不存在或已解散！");
        }
        if (!group.getType().equals("1"))
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "只有超级群可以创建频道");
        LambdaQueryWrapper<MeltCloudChannel> wrapper = Wrappers.lambdaQuery(MeltCloudChannel.class)
                .eq(MeltCloudChannel::getGroupId, channelDTO.getGroupId()).eq(MeltCloudChannel::getChannelStatus, 0);
        long count = channelService.count(wrapper);
        if (count >= 50l) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "超级群中最多可创建50个频道");
        }
        MeltCloudChannel channel = BeanUtil.copyProperties(channelDTO, MeltCloudChannel.class);
        String channelId = IdUtil.getSnowflakeNextIdStr();
        channel.setChannelId(channelId);
        channel.setCreatorUserId(currentUserId);
        channel.setCreateTime(new Date());
        channel.setUnpushLevel(0);
        channelService.save(channel);
        UltraGroupModel param = new UltraGroupModel()
                .setId(String.valueOf(channelDTO.getGroupId())).setBusChannel(channelId).setType(channelDTO.getType());
        Result result = busChannel.add(param);
        if (SendUtil.requestSuccess(result)) {
            GroupNotificationMessageDTO dto = GroupNotificationMessageDTO.builder()
                    .senderId("0").operatorUserId(currentUserId).message("创建频道成功").targetId(Arrays.asList(StrUtil.toString(channelDTO.getGroupId()))).operation("通知消息").channelId(channelId)
                    .build();
            rongYunMsgService.sendUltraGroupAdvice(dto);
            return success();
        }
        throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "创建频道失败");
    }


    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity delete(Long id) throws Exception {
        MeltCloudChannel one = channelService.getById(id);
        if (Objects.isNull(one)){
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "该频道不存在！");
        }
        if(one.getChannelId().equals("RCDefault"))
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "默认频道不可删除！");
        String currentUserId = operationPermissionVerify(one.getGroupId(), true, one.getChannelId());
        ultraGroupExpireCheck(one.getGroupId(), currentUserId, one.getChannelId());
        one.setChannelStatus(1);
        channelService.updateById(one);
        // 删除频道成员
        channelUserService.update(Wrappers.lambdaUpdate(MeltCloudChannelUser.class).set(MeltCloudChannelUser::getIsDel, 1)
                .eq(MeltCloudChannelUser::getGroupId, one.getGroupId()).eq(MeltCloudChannelUser::getChannelId, one.getChannelId()));
        // 删除频道与用户组的绑定关系
        channelUserGroupService.remove(Wrappers.lambdaQuery(MeltCloudChannelUserGroup.class)
                .eq(MeltCloudChannelUserGroup::getGroupId, one.getGroupId()).eq(MeltCloudChannelUserGroup::getChannelId, one.getChannelId()));
        UltraGroupModel model = new UltraGroupModel().setId(String.valueOf(one.getGroupId())).setBusChannel(one.getChannelId());
        Result result = busChannel.remove(model);
        if (SendUtil.requestSuccess(result))
            return success();
        throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "删除频道失败");
    }


    public ServerResponseEntity<List<MeltCloudChannel>> getChannelListByGroupId(Long groupId) throws Exception {
        LambdaQueryWrapper<MeltCloudChannel> wrapper = Wrappers.lambdaQuery(MeltCloudChannel.class)
                .eq(MeltCloudChannel::getGroupId, groupId).eq(MeltCloudChannel::getChannelStatus, 0);
        List<MeltCloudChannel> list = channelService.list(wrapper);
        Result result = busChannel.getList(String.valueOf(groupId), 1, 50);
        return success(list);
    }
    
    /**
     * 设置群/频道默认免打扰
     * @param param
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity setNoDisturb(GroupChannelDTO param) throws Exception {
        String channelId = "";
        if (StringUtils.isEmpty(param.getChannelId())) {
            MeltCloudGroup group = groupService.getById(param.getGroupId());
            if (!group.getType().equals("1")) {
                throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "该群非超级群聊！");
            }
            if (group == null || group.getIsDismiss().equals("1")) {
                throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "超级群不存在或已解散！");
            }
            String userId = operationPermissionVerify(param.getGroupId(), true, null);
            ultraGroupExpireCheck(param.getGroupId(), userId, null);
            group.setUnpushLevel(param.getUnpushLevel());
            groupService.updateById(group);
        } else {
            channelId = param.getChannelId();
            MeltCloudChannel channel = getChannel(param.getGroupId(), channelId);
            String userId = operationPermissionVerify(param.getGroupId(), false, channelId);
            ultraGroupExpireCheck(param.getGroupId(), userId, channelId);
            if (!channel.getCreatorUserId().equals(userId)) {
                throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "您并非频道创建者！");
            }
            channel.setUnpushLevel(param.getUnpushLevel());
            channelService.updateById(channel);
        }
        Result result = notdisturb.set(param.getGroupId().toString(), param.getUnpushLevel(), channelId);
        if (SendUtil.requestSuccess(result))
            return success();
        throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "群频道设置免打扰失败");
    }


    /**
     * 查询默认免打扰配置
     * @param groupId
     * @param channelId
     * @return
     * @throws Exception
     */
    public ServerResponseEntity getNoDisturb(Long groupId, String channelId) throws Exception {
        NotdisturbStatusResult result = (NotdisturbStatusResult) notdisturb.get(groupId.toString(), StringUtils.isEmpty(channelId) ? "" : channelId);
        if (SendUtil.requestSuccess(result)) {
            if (StringUtils.isEmpty(channelId)) {
                MeltCloudGroup group = groupService.getById(groupId);
                if (!group.getUnpushLevel().equals(result.getUnpushLevel())) {
                    group.setUnpushLevel(result.getUnpushLevel());
                    groupService.updateById(group);
                }
            } else {
                MeltCloudChannel channel = getChannel(groupId, channelId);
                if (!channel.getUnpushLevel().equals(result.getUnpushLevel())) {
                    channel.setUnpushLevel(result.getUnpushLevel());
                    channelService.updateById(channel);
                }
            }
            return success(result);
        }
        throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "群频道免打扰配置获取失败");
    }

    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity channelTypeChange(ChannelDTO param) throws Exception {
        if (Objects.isNull(param.getGroupId()) || StringUtils.isEmpty(param.getChannelId()) || Objects.isNull(param.getType())) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "超级群聊、频道、类型均不能为空！");
        }
        if (param.getChannelId().equals("RCDefault"))
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "默认频道不可变更频道！");
        MeltCloudChannel channel = getChannel(param.getGroupId(), param.getChannelId());
        String userId = operationPermissionVerify(param.getGroupId(), true, param.getChannelId());
        ultraGroupExpireCheck(param.getGroupId(), userId, param.getChannelId());
        if (channel.getType().equals(param.getType())) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "与原类型一致！");
        }
        channel.setType(param.getType());
        channelService.updateById(channel);

        UltraGroupModel model = new UltraGroupModel().setId(String.valueOf(param.getGroupId())).setBusChannel(param.getChannelId()).setType(param.getType());
        Result result = busChannel.change(model);
        if (SendUtil.requestSuccess(result))
            return success();
        throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "变更频道类型失败");
    }


    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity addPrivateUsers(ChannelDTO param) throws Exception {
        if (Objects.isNull(param.getGroupId()) || StringUtils.isEmpty(param.getChannelId())) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "超级群聊、频道均不能为空！");
        }
        String currentUserId = operationPermissionVerify(param.getGroupId(), false, null);
        ultraGroupExpireCheck(param.getGroupId(), currentUserId, param.getChannelId());
        MeltCloudGroup group = groupService.getById(param.getGroupId());
        if (group == null || group.getIsDismiss().equals("1")) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "超级群不存在或已解散！");
        }
        MeltCloudChannel one = getChannel(param.getGroupId(), param.getChannelId());
        if (one.getType() != 1) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "只有私有频道需要加入用户！");
        }
        List<String> userIdList = param.getUserIds().stream().distinct().collect(Collectors.toList());
        if (CollUtil.isEmpty(userIdList) || userIdList.size() > 20) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "用户不能为空或大于20人！");
        }
        List<MeltCloudChannelUser> list = new ArrayList<>();
        for (String userId : userIdList) {
            MeltCloudGroupUser groupUser = groupUserService.getOne(Wrappers.lambdaQuery(MeltCloudGroupUser.class)
                    .eq(MeltCloudGroupUser::getGroupId, param.getGroupId()).eq(MeltCloudGroupUser::getUserId, userId).eq(MeltCloudGroupUser::getIsDel, 0));
            if (groupUser == null) {
                MeltCloudUser user = userService.getById(userId);
                throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, user.getUserName()+"不在此超级群成员中！");
            }
            MeltCloudChannelUser channelUser = MeltCloudChannelUser.builder().groupId(param.getGroupId()).channelId(param.getChannelId()).userId(userId).build();
            list.add(channelUser);
        }
        channelUserService.saveBatch(list);
        String userIds = userIdList.stream().collect(Collectors.joining(","));
        UltraGroupMember member = new UltraGroupMember(userIds, null);
        UltraGroupMember[] members = new UltraGroupMember[]{member};
        UltraGroupModel model = new UltraGroupModel()
                .setId(String.valueOf(param.getGroupId())).setBusChannel(param.getChannelId()).setMembers(members);
        Result result = busChannel.privateUserAdd(model);
        if (!SendUtil.requestSuccess(result)) 
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "添加私有频道成员失败！");
        MeltCloudUser user = userService.getById(currentUserId);
        List<MeltCloudUser> cloudUserList = userService.listByIds(userIdList);
        String names = cloudUserList.stream().map(MeltCloudUser::getUserName).collect(Collectors.joining("、"));
        String message = String.format("%s邀请了%s进入了频道", user.getUserName(), names);
        GroupNotificationMessageDTO dto = GroupNotificationMessageDTO.builder()
                .senderId("0").operatorUserId(currentUserId)
                .message(message).targetId(Arrays.asList(param.getGroupId().toString()))
                .channelId(param.getChannelId()).operation("邀请通知消息")
                .build();
        rongYunMsgService.sendUltraGroupAdvice(dto);
        return success();
    }


    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity delPrivateUsers(ChannelDTO param) throws Exception {
        if (Objects.isNull(param.getGroupId()) || StringUtils.isEmpty(param.getChannelId())) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "超级群聊、频道均不能为空！");
        }
        if (CollUtil.isEmpty(param.getUserIds())) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "请选择要移出频道的用户！");
        }
        String currentUserId = operationPermissionVerify(param.getGroupId(), true, param.getChannelId());
        MeltCloudChannel one = getChannel(param.getGroupId(), param.getChannelId());
        ultraGroupExpireCheck(param.getGroupId(), currentUserId, param.getChannelId());
        List<String> userIdList = param.getUserIds().stream().distinct().collect(Collectors.toList());
        if (CollUtil.isEmpty(userIdList) || userIdList.size() > 20) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "用户不能为空或大于20人！");
        }
        if (userIdList.contains(one.getCreatorUserId())) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "不能移出创建者！");
        }
        String userIds = userIdList.stream().collect(Collectors.joining(","));
        UltraGroupMember member = new UltraGroupMember(userIds, null);
        UltraGroupMember[] members = new UltraGroupMember[]{member};
        UltraGroupModel model = new UltraGroupModel().setId(String.valueOf(param.getGroupId())).setBusChannel(param.getChannelId()).setMembers(members);
        Result result = busChannel.privateUserRemove(model);
        if (!SendUtil.requestSuccess(result))
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "删除私有频道成员失败！");
        channelUserService.update(Wrappers.lambdaUpdate(MeltCloudChannelUser.class).set(MeltCloudChannelUser::getIsDel, 1)
                .eq(MeltCloudChannelUser::getGroupId, param.getGroupId()).eq(MeltCloudChannelUser::getChannelId, param.getChannelId()).in(MeltCloudChannelUser::getUserId, userIdList));
        List<MeltCloudUser> cloudUserList = userService.listByIds(userIdList);
        String names = cloudUserList.stream().map(MeltCloudUser::getUserName).collect(Collectors.joining("、"));
        String message = String.format("%s退出频道", names);
        GroupNotificationMessageDTO dto = GroupNotificationMessageDTO.builder()
                .senderId("0")
                .operatorUserId(currentUserId)
                .message(message)
                .targetId(Arrays.asList(param.getGroupId().toString()))
                .channelId(param.getChannelId())
                .operation("通知消息")
                .build();
        rongYunMsgService.sendUltraGroupAdvice(dto);
        return success();
    }
    
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity quitChannel(ChannelDTO param) throws Exception {
        if (Objects.isNull(param.getGroupId()) || StringUtils.isEmpty(param.getChannelId())) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "超级群聊、频道均不能为空！");
        }
        String userId = operationPermissionVerify(param.getGroupId(), false, null);
        ultraGroupExpireCheck(param.getGroupId(), userId, param.getChannelId());
        MeltCloudChannel one = getChannel(param.getGroupId(), param.getChannelId());
        if (userId.equals(one.getCreatorUserId())) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "创建者不能退出！");
        }
        UltraGroupMember member = new UltraGroupMember(userId, null);
        UltraGroupMember[] members = new UltraGroupMember[]{member};
        UltraGroupModel model = new UltraGroupModel()
                .setId(String.valueOf(param.getGroupId())).setBusChannel(param.getChannelId()).setMembers(members);
        Result result = busChannel.privateUserRemove(model);
        if (!SendUtil.requestSuccess(result))
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "退出频道失败！");
        channelUserService.update(Wrappers.lambdaUpdate(MeltCloudChannelUser.class).set(MeltCloudChannelUser::getIsDel, 1)
                .eq(MeltCloudChannelUser::getGroupId, param.getGroupId()).eq(MeltCloudChannelUser::getChannelId, param.getChannelId()).eq(MeltCloudChannelUser::getUserId, userId));
        MeltCloudUser cloudUserList = userService.getById(userId);
        String message = String.format("%s退出频道", cloudUserList.getUserName());
        GroupNotificationMessageDTO dto = GroupNotificationMessageDTO.builder()
                .senderId("0")
                .operatorUserId(userId)
                .message(message)
                .targetId(Arrays.asList(param.getGroupId().toString()))
                .channelId(param.getChannelId())
                .operation("通知消息")
                .build();
        rongYunMsgService.sendUltraGroupAdvice(dto);
        return success();
    }
    
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity transferChannel(ChannelDTO param) {
        if (Objects.isNull(param.getGroupId()) || StringUtils.isEmpty(param.getChannelId())) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "超级群聊、频道均不能为空！");
        }
        if (StringUtils.isEmpty(param.getUserId())) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "接管用户不能为空！");
        }
        String currentUserId = operationPermissionVerify(param.getGroupId(), false, null);
        ultraGroupExpireCheck(param.getGroupId(), currentUserId, param.getChannelId());
        MeltCloudChannel one = getChannel(param.getGroupId(), param.getChannelId());
        if (!currentUserId.equals(one.getCreatorUserId())) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "非创建者不能操作！");
        }
        one.setCreatorUserId(param.getUserId());
        channelService.updateById(one);
        return success();
    }
    
    public ServerResponseEntity getPrivateUsers(Long groupId, String channelId, String currentUserId) {
        MeltCloudChannel one = getChannel(groupId, channelId);
        if (one.getType() == 0) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "公有频道成员既是超级群成员！");
        }
        List<MeltCloudUser> list = channelUserService.getPrivateUserList(groupId, channelId, currentUserId);
        return success(list);
    }

    public ServerResponseEntity getChannelList(Long groupId, String userId) {
        List<MeltCloudChannel> list = channelUserService.getChannelList(groupId, userId);
        return success(list);
    }

    private void checkChannelMember(MeltCloudChannel one, String userId) {
        MeltCloudChannelUser channelUser = channelUserService.getOne(Wrappers.lambdaQuery(MeltCloudChannelUser.class)
                .eq(MeltCloudChannelUser::getGroupId, one.getGroupId()).eq(MeltCloudChannelUser::getChannelId, one.getChannelId()).eq(MeltCloudChannelUser::getUserId, userId).eq(MeltCloudChannelUser::getIsDel, 0));
        if (Objects.isNull(channelUser)) {
            List<MeltCloudChannelUserGroup> list = channelUserGroupService.list(Wrappers.lambdaQuery(MeltCloudChannelUserGroup.class)
                    .eq(MeltCloudChannelUserGroup::getGroupId, one.getGroupId()).eq(MeltCloudChannelUserGroup::getChannelId, one.getChannelId()));
            Set<Long> userGroupIds = list.stream().map(MeltCloudChannelUserGroup::getUserGroupId).collect(Collectors.toSet());
            List<MeltCloudUsergroupUser> userList = usergroupUserService.list(Wrappers.lambdaQuery(MeltCloudUsergroupUser.class)
                    .eq(MeltCloudUsergroupUser::getGroupId, one.getGroupId()).in(MeltCloudUsergroupUser::getUserGroupId, userGroupIds).eq(MeltCloudUsergroupUser::getIsDel, 0).eq(MeltCloudUsergroupUser::getUserId, userId));
            if (CollUtil.isEmpty(userList)) {
                throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "您不是该频道成员！");
            }
        }
    }

    /**
     * 管理者操作权限
     * @param groupId
     * @param isManger
     * @param channelId
     * @return
     */
    private String operationPermissionVerify(Long groupId, boolean isManger, String channelId) {
        String currentUserId = "";
        UserInfoInTokenBO userTokenBO = AuthUserContext.get();
        if (userTokenBO.getSysType().equals(1)) {
            currentUserId = "shop_" + userTokenBO.getUserId();
        } else if (userTokenBO.getSysType().equals(2)) {
            currentUserId = "plat_" + userTokenBO.getUserId();
        } else if (userTokenBO.getSysType().equals(0)) {
            currentUserId = userTokenBO.getUserId();
        }
        if (isManger) {
            MeltCloudGroup group = groupService.getById(groupId);
            if (group == null || group.getIsDismiss().equals("1")) {
                throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "该群不存在或已解散！");
            }
            if (!group.getCreatorUserId().equals(currentUserId)) {
                MeltCloudGroupUser groupUser = groupUserService.getOne(Wrappers.lambdaQuery(MeltCloudGroupUser.class)
                        .eq(MeltCloudGroupUser::getGroupId, groupId).eq(MeltCloudGroupUser::getUserId, currentUserId).eq(MeltCloudGroupUser::getIsManage, 1));
                if (Objects.isNull(groupUser)) {
                    if (StringUtils.isEmpty(channelId)) {
                        throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "您非群主或管理员不能操作！");
                    } else {
                        MeltCloudChannel channel = getChannel(groupId, channelId);
                        if (!channel.getCreatorUserId().equals(currentUserId)) {
                            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "您非群主管理员或频道创建者不能操作！");
                        }
                    }
                }
            }
        }
        return currentUserId;
    }


    /**
     * 检查超级群到期操作权限
     * @param groupId 群id
     * @param currentUserId 当前人id
     * @param channelId 频道id
     * @return
     */
    private void ultraGroupExpireCheck(Long groupId, String currentUserId, String channelId) {
        MeltCloudGroup group = groupService.getById(groupId);
        if (group.getType().equals("1") && group.getIsArrears() == 1) {
            if (StringUtils.isEmpty(currentUserId)) {
                throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "操作人不能为空！");
            }
            if (group.getCreatorUserId().equals(currentUserId)) {
                throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "该群已欠费，不能操作！");
            } else {
                MeltCloudGroupUser groupUser = groupUserService.getOne(Wrappers.lambdaQuery(MeltCloudGroupUser.class)
                        .eq(MeltCloudGroupUser::getGroupId, groupId).eq(MeltCloudGroupUser::getUserId, currentUserId).eq(MeltCloudGroupUser::getIsManage, 1));
                if (Objects.nonNull(groupUser)) {
                    throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "该群已欠费，不能操作！");
                } else {
                    if (StringUtils.isNotEmpty(channelId)) {
                        MeltCloudChannel one = getChannel(groupId, channelId);
                        if (one.getCreatorUserId().equals(currentUserId)) {
                            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "该群已欠费，不能操作！");
                        }
                    }
                }
            }
        }
    }

    
    private MeltCloudChannel getChannel(Long groupId, String channelId) {
        MeltCloudChannel one = channelService.getOne(Wrappers.lambdaQuery(MeltCloudChannel.class).eq(MeltCloudChannel::getGroupId, groupId).eq(MeltCloudChannel::getChannelId, channelId).eq(MeltCloudChannel::getChannelStatus, 0));
        if (one == null) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "该频道不存在！");
        }
        return one;
    }
    
    

}




